//
//  DisplayView.swift
//  PhotoBrowser
//
//  Created by meng on 16/5/17.
//  Copyright © 2016年 leotao. All rights reserved.
//

import UIKit


class DisplayView: UIScrollView {
    var index:Int = 0;
    var photo:Photo?;
    var progressView = CircleProgressView(frame: CGRect.zero);
    
    var imageView:UIImageView!
    
    var indexLabel:UILabel!
    var zoomToFill = false;
    weak var browser:PhotoBrowser!
    
    init(browser: PhotoBrowser) {
        
        
        imageView = UIImageView();
        imageView.contentMode = .Center;
//        imageView.backgroundColor = UIColor.blackColor();
        
        super.init(frame: CGRect.zero);
        self.backgroundColor = UIColor.blackColor();
        addSubview(imageView);
        
        progressView.hidden = true;
        addSubview(progressView);
        
        self.browser = browser;
        
        self.delegate = self;
        self.showsVerticalScrollIndicator = false;
        self.showsHorizontalScrollIndicator = false;
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DisplayView.receiveProgress(_:)), name: ProgressChangeNotification, object: nil);
        
        
//        let gesture = UITapGestureRecognizer(target: self, action: #selector(DisplayView.tap));
//        self.addGestureRecognizer(gesture);
        
        NSLog("(%p) init", self);
    }
    
//    func test(<#parameters#>) -> <#return type#> {
//        <#function body#>
//    }
    
    func tap() {
        browser.dismissViewControllerAnimated(true, completion: nil);
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews();
        
        let boundsSize = self.bounds;
        var frameToCenter = imageView.frame;
        
        // 水平居中
        if frameToCenter.width < boundsSize.width {
            frameToCenter.origin.x = CGFloat(floorf((Float(bounds.width) - Float(frameToCenter.width)) * 0.5));
        } else {
            frameToCenter.origin.x = 0;
        }
        
        if frameToCenter.height < boundsSize.height {
            frameToCenter.origin.y = CGFloat(floorf((Float(bounds.height) - Float(frameToCenter.height)) * 0.5));
        } else {
            frameToCenter.origin.y = 0;
        }
        
        // frameToCenter相对于之前发生了改变则重新赋值
        if !CGRectEqualToRect(imageView.frame, frameToCenter) {
            imageView.frame = frameToCenter;
        }
        
        let width:CGFloat = 60;
        let height = width;
        self.progressView.frame = CGRectMake((bounds.width - width) * 0.5, (bounds.height - height) * 0.5, width, height);
        
//        print("imageview.frame = \(imageView.frame)");
    }
    
    func prepareToReuse() {
        progressView.progress = 0;
        imageView.image = nil;
        progressView.hidden = true;
        self.photo?.image = nil;
    }
    
    func setPhoto(photo:Photo) {
        self.photo = photo;
        
        let image = browser.imageForPhoto(self.photo);
        
        if image != nil {
            displayImage(image);
        } else {
            displayProgressView();
        }
    }
    
    
    
    func displayImage(image: UIImage?) {
        self.progressView.hidden = true;
        // 有图片并且imageView未设置图片的时候才执行计算
        if self.photo != nil && self.imageView.image == nil {
            self.maximumZoomScale = 1.0;
            self.minimumZoomScale = 1.0;
            self.zoomScale = 1.0;
            self.contentSize = CGSizeZero;
            
            if image != nil {
                
                self.imageView.image = image;
                self.imageView.frame.origin = CGPointZero;
                self.imageView.frame.size = image!.size;
                
                self.contentSize = self.imageView.frame.size;
                setMaxMinZoomScaleForCurrentBounds();
            }
        } else {
            print("下载出错");
        }
        
        setNeedsLayout();
    }
    
    func displayProgressView() {
        self.progressView.hidden = false;
    }
    
    func hideProgressView() {
        self.progressView.hidden = true;
    }
    
    func setMaxMinZoomScaleForCurrentBounds() {
        self.maximumZoomScale = 1;
        self.minimumZoomScale = 1;
        self.zoomScale = 1;
        
        if imageView.image == nil {
            return;
        }
        
        imageView.frame.origin = CGPointZero;
        let boundsSize = self.bounds.size;
        let imageSize = imageView.image!.size;
        
        let xScale = boundsSize.width / imageSize.width;
        let yScale = boundsSize.height / imageSize.height;
        
        var minScale = min(xScale, yScale);
        var maxScale:CGFloat = 3.0;
        
        if UI_USER_INTERFACE_IDIOM() == .Pad {
            maxScale = 4;
        }
        
        if minScale > maxScale {
            maxScale = minScale * 1.5;
        }
        
        if xScale >= 1 && yScale >= 1 && !zoomToFill {
            minScale = 1;
        }
        
        self.minimumZoomScale = minScale;
        self.maximumZoomScale = maxScale;
        
        self.zoomScale = minScale;
        self.scrollEnabled = false;
    }
    
    func receiveProgress(noti: NSNotification) {
        dispatch_async(dispatch_get_main_queue()) { 
            let pho = noti.object as! Photo;
            if pho.photoURL!.absoluteString == self.photo!.photoURL!.absoluteString {
                let progress = noti.userInfo!["progress"] as! CGFloat;
                
                if progress < 1 {
                    self.progressView.progress = progress;
                } else {
                    self.progressView.hidden = true;
                }
            }
        };
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self);
        NSLog("(%p) deinit", self);
    }
}

extension DisplayView: UIScrollViewDelegate {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView;
    }
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        setNeedsLayout();
        layoutIfNeeded();
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        scrollView.scrollEnabled = true;
    }
}
